import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef, useState } from 'react'
import { ScrollViewWrapper } from "./style"
import IconLeftBtn from "@/assets/svg/icon-left-btn"
import IcoRightBtn from "@/assets/svg/icon-right-btn"

const ScrollView = memo((props) => {

  const [showRight, setShowRight] = useState(false)
  const [showLeft, setShowLeft] = useState(false)
  const totalDistanceRef = useRef(0)
  // 记录索引
  const [posIndex, setPosIndex] = useState(0)

  const scrollSlotRef = useRef()

  useEffect(() => {
    const scrollWidth = scrollSlotRef.current.scrollWidth
    const clientWidth = scrollSlotRef.current.clientWidth
    const distance = scrollWidth - clientWidth
    // 超出宽度
    setShowRight(distance > 0 && true)
    setShowLeft(distance < 0 && true)
    totalDistanceRef.current = distance
  }, [props.children])

  function controlClickHandle(isShow) {
    const newIndex = isShow ? posIndex + 1 : posIndex - 1
    const sroll = scrollSlotRef.current.children[newIndex]
    scrollSlotRef.current.style.transform = `translate(-${sroll.offsetLeft}px)`
    setPosIndex(newIndex)
    setShowRight(totalDistanceRef.current > sroll.offsetLeft)
    setShowLeft(sroll.offsetLeft > 10)
  }

  return (
    <ScrollViewWrapper>
      {showLeft && (
        <div className='icon1' onClick={() => controlClickHandle(false)}>
          <IconLeftBtn></IconLeftBtn>
        </div>
      )}
      {showRight && (
        <div className='icon2' onClick={() => controlClickHandle(true)}>
          <IcoRightBtn></IcoRightBtn>
        </div>
      )}
      <div className="box" >
        <div className="slot" ref={scrollSlotRef} >
          {props.children}
        </div>
      </div>
    </ScrollViewWrapper>
  )
})

ScrollView.propTypes = {}

export default ScrollView